<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('post_views', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable()->comment('用户ID（游客为空）');
            $table->unsignedBigInteger('post_id')->comment('文章ID');
            $table->string('ip_address', 45)->comment('访问IP地址');
            $table->string('user_agent', 500)->nullable()->comment('浏览器信息');
            $table->unsignedInteger('read_duration')->default(0)->comment('阅读时长（秒）');
            $table->unsignedInteger('read_progress')->default(0)->comment('阅读进度（百分比）');
            $table->timestamp('viewed_at')->useCurrent()->comment('浏览时间');
            $table->timestamp('last_viewed_at')->nullable()->comment('最后浏览时间');
            $table->unsignedInteger('view_count')->default(1)->comment('浏览次数');

            // 添加外键约束
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

            // 添加索引
            $table->index(['user_id', 'viewed_at']);
            $table->index(['post_id', 'viewed_at']);
            $table->index(['user_id', 'post_id']);
            $table->index(['ip_address', 'post_id']);

            // 唯一约束：同一用户对同一文章只记录一条，但会更新浏览次数和时间
            $table->unique(['user_id', 'post_id'], 'unique_user_post_view');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('post_views');
    }
};